/*
 * bsp_timer.c
 *
 *  Created on: 2025 Feb 17
 *      Author: SFLY
 */
#include "bsp_timer.h"
#include "bsp_board_config.h"

//extern __interrupt void timer0_interrupt(void);
uint32_t global_sys_time_count = 0;
void Bsp_Timer_Init(void)
{
   SysCtl_enablePeripheral(SYSCTL_PERIPH_CLK_CPU0_TIMER0);
   uint32_t temp = 0xFFFFFFFF;//(uint32_t)(DEVICE_SYSCLK_FREQ_MHZ * (float)Motor_SYS_TIMER0_INT_US - 1);
   CPUTimer_setPreScaler(CPUTIMER0_BASE, 0);
   CPUTimer_setEmulationMode(CPUTIMER0_BASE, CPUTIMER_EMULATIONMODE_RUNFREE);
   CPUTimer_setPeriod(CPUTIMER0_BASE, temp);
   CPUTimer_stopTimer(CPUTIMER0_BASE);
   CPUTimer_reloadTimerCounter(CPUTIMER0_BASE);
//   Interrupt_register(INT_TIMER0,&timer0_interrupt);
//   CPUTimer_enableInterrupt(CPUTIMER0_BASE);
//   Interrupt_enable(INT_TIMER0);
   // Starts CPU-Timer
   CPUTimer_startTimer(CPUTIMER0_BASE);
}

float Bsp_Calculate_Delta_Count(uint32_t current, uint32_t previous) {
    uint32_t reload_value =0xFFFFFFFF;
    float result = 0.0;
    if (current <= previous) {
        result = (float)(previous - current)*INV_DEVICE_SYSCLK_FREQ;
        return result;  // 未溢出
    } else {
        result  = (float)(previous + (reload_value - current + 1))*INV_DEVICE_SYSCLK_FREQ;
        return result;  // 溢出处理
    }
}

uint32_t Bsp_Get_Timer_Count(void)
{
    return CPUTimer_getTimerCount(CPUTIMER0_BASE);
}
//float Bsp_Get_Timer_Count(void)
//{
//    //缺少处理溢出，之后增加
//    if(global_sys_time_count==4294967296)
//    {
//        overflow_flag++;
//    }
//   return (global_sys_time_count*Motor_SYS_TIMER0_INT_US*1e-6f);
//}

//void timer0_interrupt(void)
//{
//    global_sys_time_count++;
//    CPUTimer_clearInterrupt(CPUTIMER0_BASE);
//}
